package net.moonj.UDPUI;

import java.io.IOException;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;

import io.netty.channel.socket.DatagramPacket;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import net.moonj.UDPUI.udp.UDPServer;

/**
 * Hello world!
 *
 */
public class App extends Application {
	
	@FXML
	public ToggleButton listen;
	@FXML
	public ToggleButton echoMode;
	@FXML
	public TextField remoteHost;
	@FXML
	public TextField remotePort;
	@FXML
	public TextField listenPort;
	@FXML
	public TextArea console;
	@FXML
	public TextField content;
	@FXML
	public Button send;
	@FXML
	Label echoRCVD;
	@FXML
	Button clear;
	@FXML
	TextField repeat;
	@FXML
	Button clearConsole;
	
	
	public AtomicInteger receivedEchoCount = new AtomicInteger(0);
	
	public AtomicInteger sendCount = new AtomicInteger(0);
	
	
	private static App instance ;
	
	public UDPServer udpServer;
	
	public static App instance(){
		return instance;
	}
	
	public static void main(String[] args) {
		launch(args);
	}
	@Override
	public void start(Stage primaryStage) throws Exception {
		instance = this;
		udpServer = new UDPServer();
		FXMLLoader loader = new FXMLLoader(getClass().getResource("UI.fxml"));
        loader.setController(this);
        Pane myPane = loader.load();
        Scene myScene = new Scene(myPane);
        primaryStage.setScene(myScene);
        
        //register event
        listen.setOnAction(e->{
        	if(listen.isSelected()){
        		doListen();
        	}else{
        		udpServer.closeListenSync();
        		appendln("解除监听");
        		listenPort.setEditable(true);
        	}
        });
        //发送
        send.setOnMouseClicked(e->{
        	if(content.getText().equals("")){
        		appendln("请输入消息");
        		return ;
        	}
        	
        	int repeatCount = 1;
        	
        	try{
        		repeatCount = Integer.parseInt(repeat.getText());
        	}catch (Exception ex) {
        		repeatCount = 1;
			}
        	if(repeatCount<=0){
        		repeatCount = 1;
        	}
        	
        	for(int i =0 ; i < repeatCount ; i++){
        		try{
            		udpServer.sendAssignmentByOS(content.getText(), remoteHost.getText(), Integer.parseInt(remotePort.getText()));
            		appendln("已发送");
            		//计数
            		App.instance().sendCount.incrementAndGet();
            		App.instance().changeCountDisplay();
            		
            	}catch(UnknownHostException unkHost){
            		unkHost.printStackTrace();
            		appendln("未知主机 请检查remote host内容");
            	} catch (NumberFormatException e1) {
            		e1.printStackTrace();
            		appendln("remote host内必须是数字");
    			} catch (IOException e1) {
    				e1.printStackTrace();
    				appendln("IOException 发送失败");
    			}
        	}
        });
        
        //clear counter
        clear.setOnMouseClicked(e->{
        	receivedEchoCount.set(0);
        	sendCount.set(0);
        	changeCountDisplay();
        });
        
        //clear console
        clearConsole.setOnMouseClicked(e->{
        	console.setText("");
        });
        
        //关闭时关闭线程组
        EventHandler<WindowEvent> defaultClose = primaryStage.getOnCloseRequest();
        primaryStage.setOnCloseRequest(e->{
        	udpServer.close();
        	if(defaultClose!=null){
        		defaultClose.handle(e);
        	}
        });
        
        doListen();
        
        primaryStage.setTitle("UDP interface");
        primaryStage.show();
	}
	
	public static void appendln(String text){
		Platform.runLater(()->{
			instance.console.appendText(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ").format(new Date())+text+"\n");
		});
	}
	
	public static boolean echoOpen(){
		return instance.echoMode.isSelected();
	}
	
	
	public static void handlePacket(String hostname,int port,String content){
		appendln("接收到来自"+hostname+":"+port+"的udp包\n内容["+content+"]");
	}
	private void doListen(){
		try{
    		udpServer.listenSync(Integer.parseInt(listenPort.getText()));
    		appendln("开始监听 端口:"+listenPort.getText());
    		listenPort.setEditable(false);
    	}catch(Exception ex){
    		ex.printStackTrace();
    		appendln("监听失败 请检查listen port是否填写正确");
    		listen.setSelected(false);
    		listenPort.setEditable(true);
    	}
	}

	public void changeCountDisplay() {
		Platform.runLater(()->{
			echoRCVD.setText("received echo "+receivedEchoCount.get()+"/"+sendCount.get()+" "+((int)(receivedEchoCount.get()*1.0f/sendCount.get()*100))+"%");
		});
	}
}
